
import os
import ansible_runner
import re
#os.environ['ANSIBLE_VAULT_PASSWORD_FILE'] = '.vault_pass'
back_result=[]
def run_playbook_with_cert(playbook_path, inventory_path):
    # 配置Runner环境变量
    extravars = {
         'ansible_fact_caching_enabled': False,
         'ansible_user': 'root',
         'ansible_password': 'Emotibot@1',
         'ansible_ssh_port': 22,
    #     'ANSIBLE_VAULT_PASSWORD_FILE': '/root/test/.vault_pass',
        'ANSIBLE_HOST_KEY_CHECKING': 'False'
    }
    
    # 执行Playbook
    runner = ansible_runner.run(
        playbook=playbook_path,
        inventory=inventory_path,
        extravars=extravars,
        quiet=True,  # 显示详细输出
        json_mode=True  # 返回JSON格式结果
    )
    
    # 处理执行结果
    try:
        if runner.status == 'failed':
            print("Ansible Playbook执行成功")
            for event in runner.events:
                if event['event'] == 'runner_on_ok':
                   for k,v in event.items():
                       if k == "event_data":
                          result=(v["task"],v["remote_addr"],"successful")
                          back_result.append(result)
                          print("\033[32m"+str(result)+"\033[0m")
                else:
                   for k,v in event.items():
                       if k == "stdout":
                          if re.search("fatal",v):
                             ss=(v.split("=>")[0].split(":")[1])
                             to_remove = "[]"
                             result = re.sub(f"[{re.escape(to_remove)}]", "", ss)
                             resultbak=result,v.split("=>")[1].split(",")[1],"failed"
                             back_result.append(resultbak)
                             print ("\033[31m"+str(resultbak)+"\033[0m")
          #  print(f"执行失败，返回码: {runner.rc}")
          #  print("错误输出:", runner.msg)
    except Exception as e:
            print("错误输出:", runner.stderr)
if __name__ == '__main__':
    run_playbook_with_cert(
       # playbook_path='/root/test/adduser.yaml',  # 替换为你的Playbook路径
        playbook_path='/root/test/deploy.yaml',  # 替换为你的Playbook路径
        inventory_path='/root/test/hosts.ini',  # 替换为Inventory文件路径
   #     ssh_private_key='~/.ssh/id_rsa'  # 替换为你的SSH私钥路径
    )

    print (back_result)
